<template>
    <!-- 添加或修改对话框 -->
    <el-dialog v-model="open" :title="form.essayid?'修改数据':'新增数据'" width="1000" :close-on-click-modal="false">
        <el-form ref="formRef" :model="form" label-width="80px">
            <el-form-item label="文章上级id" prop="titleid" :rules="[{ required: true, message: '该值不能为空', trigger: 'blur' }]">
                <el-input v-model="form.titleid" placeholder="请输入文章上级id" />
            </el-form-item>

            <el-form-item label="文章名称" prop="title" :rules="[{ required: true, message: '该值不能为空', trigger: 'blur' }]">
                <el-input v-model="form.title" placeholder="请输入文章名称" />
            </el-form-item>

            <el-form-item label="文章内容" prop="brief" :rules="[{ required: true, message: '该值不能为空', trigger: 'blur' }]">
                <editor   @update:modelValue="editorContentChange" v-model:modelValue="form.brief" :minHeight="300"></editor>
                 <el-input v-model="form.brief"  v-show="false" />
            </el-form-item>

            <el-form-item v-model="form.imageUrl" label="封面图片" prop="imageUrl">
                <el-upload
                    class="avatar-uploader"
                    :action="imageUploadUrl"
                    :headers="data.header"
                    :data="data.ossdata"
                    name="imgFile"
                    :show-file-list="false"
                    :on-success="handleAvatarSuccess"
                    :before-upload="beforeAvatarUpload"
                  >
                    <img v-if="form.imageUrl" :src="form.imageUrl" class="avatar" />
                    <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                  </el-upload>
            </el-form-item>

            <el-form-item label="点赞数" prop="dianzhan">
                <el-input v-model="form.dianzhan" type="textarea" placeholder="请输入点赞数" />
            </el-form-item>

            <el-form-item label="评论数" prop="comments">
                <el-input v-model="form.comments" type="textarea" placeholder="请输入评论数" />
            </el-form-item>

            <el-form-item label="发表人id" prop="userid">
                <el-input v-model="form.userid" type="textarea" placeholder="请输入发表人id" />
            </el-form-item>

            <el-form-item label="发表人地址" prop="useraddress">
                <el-input v-model="form.useraddress" type="textarea" placeholder="请输入发表人地址" />
            </el-form-item>

        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script lang="ts" setup>
import { reactive, ref, getCurrentInstance, ComponentInternalInstance } from 'vue';
import type { FormInstance, ElMessage, UploadFile } from 'element-plus';
import { AppFindZhangzhishiessayreq,FindZhangzhishiresp,Zhangzhishiaddreq} from '@/api/app/typescript/findessay';
import { editEssay,addEssay,FindByIdEssay } from '@/api/app/find/essay'
import editor from '@/components/Editor/index.vue'
import { da } from 'element-plus/es/locale';
import { getToken } from '@/utils/auth';

//图片上传地址
const imageUploadUrl =ref(import.meta.env.VITE_APP_BASE_API+'/oss/uploadImg');
const token=getToken();
//配置请求头的令牌
const header={
    header: {
        'Authorization': token
    }
} ;

//自己的定义额外参数
const data = reactive({
    header: {
        'Authorization': token
    },
    ossdata: {
        fatherPath:'images'
    }
});

// 获取当前vue3的页面this对象转换为proxy代理，查询 sys_dict_data表中的值
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
// 对话框配置
const open = ref(false);
const title = ref('');
//得到数据表单form样式对象
const formRef = ref<FormInstance>();

//声明子组件的自定义事件 https://cn.vuejs.org/api/sfc-script-setup.html#defineprops-defineemits
const emit = defineEmits(['refreshDataList']);

// 定义表单对象
const form = ref<AppFindZhangzhishiessayreq>({
    essayid: undefined,
    titleid:undefined,
    title: '',
    brief: '' ,
    imageUrl:undefined,
    dianzhan:'',
    comments:'',
    userid:'',
    useraddress:'',
    createTime:''
});


//对话框保存按钮
const submitForm = () => {
    formRef.value.validate((valid: boolean) => {
        //验证不成功
        if (!valid) {
            return false;
        }

        //修改
        if (form.value.essayid) {
            editEssay(form.value).then(resp => {
                ElMessage.success({
                    message: '修改成功',
                    duration: 500,
                    onClose: () => {
                        //关闭弹窗
                        open.value = false;
                        //调用重新查询数据操作
                        emit('refreshDataList');
                    }
                });

            });
        } else {
            //新增
            addEssay(form.value).then(resp => {
                ElMessage.success({
                    message: '新增成功',
                    duration: 500,
                    onClose: () => {
                        //关闭弹窗
                        open.value = false;
                        //调用重新查询数据操作
                        emit('refreshDataList');
                    }
                });

            });
        }

    });

};


//对话框取消按钮
const cancel = () => {
    open.value = false;
    resetFrom();
};

// 重置表单
const resetFrom = () => {
    // 清空表单样式
    if (formRef.value) {
        formRef.value.resetFields();
    }


    // 重置值
    form.value = {
        essayid: undefined,
        titleid:undefined,
        title: '',
        brief: '',
        imageUrl: undefined,
        dianzhan: '',
        comments: '',
        userid:'',
        useraddress:'',
        createTime:''
    };
};


//判断如果是修改操作，就要查询数据库，还原数据,要暴露出去
const init = (id?: number) => {

    // 重置表单数据
    resetFrom();
    // id 存在则为修改
    if (id) {
        FindByIdEssay(id).then(resp=>{
            const data:FindZhangzhishiresp=resp.data

            const dataObj:AppFindZhangzhishiessayreq=JSON.parse(JSON.stringify(data));
            form.value=dataObj;
        });
    }
    else{
        //新增数据，默认数据
        form.value={
            essayid: undefined,
            title: '',
            brief: '',
            imageUrl: undefined,
            dianzhan: '',
            comments: '',
            userid:'',
            useraddress:'',
            createTime:''
        };
    }
    open.value = true;
};

function  beforeAvatarUpload(file) {
    console.log(file);
    //允许的图片类型
    const imgType = (file.type === 'image/jpeg') || (file.type === 'image/png') || (file.type === 'image/gif');
    //文件大小3M
    const imgLimit= (file.size / 1024 / 1024) < 3;
    if (!imgType) {
        ElMessage.error("只允许jpg、png、gif格式的图片");
        return false;
    }
    if (!imgLimit) {
        ElMessage.error("上传的图片大小不能超过3MB");
        return false;
    }

    return true;
}

/** 上传图片 */
function handleAvatarSuccess(res, file)  {
    console.log(res);
    form.value.imageUrl=res.data;
    console.log(form.value.imageUrl)
};


function editorContentChange(val:string){
    form.value.brief=val
}

defineExpose({
   	init
});
</script>

